//jsgrid表格插件
$(document).ready(function () {


	 // 查询页面
    $(".search").on("click", function () {
        var starttime = $("input[name=starttime]").val();
        var endtime = $("input[name=endtime]").val();
       /* var endtime = escape($("input[name=endtime]").val());*/
        if (starttime.length <= 0 || endtime.length <= 0) {
            loadjqGrid("", "");
            alert("请选择查找日期！");
            return;
        } else {
            loadjqGrid(starttime, endtime);
        }
    });


    //打印
    $("#btnPrint").click(function () {
        //alert("printtest");
        $("#myPrintArea").printArea();
        //$("#myPrintArea").jqprint({
        //    debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
        //    importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
        //    printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
        //    operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        //});
    });


    


    $('#export').click(function () {
        var title = "值班信息";
        getXlsFromTbl('list1', 'div_list', title, true)
    });

    loadjqGrid("","");


});
	

function loadjqGrid(starttime, endtime) {
	/*$.jgrid.defaults.styleUI = 'Bootstrap';*/
	var dutyinfodata={};
	$.ajax({
		async:false, //同步骤执行，即从后台获取json数据以后才本地装载jqgrid数据
		cache:false,
		type:'POST',
		data:{
			stime:starttime,
			etime:endtime
		},
		dataType:"json",
	//	contentType: 'application/json; charset=utf-8',//设置编码格式
	//	url:"<%=request.getContextPath()%>"+"/cn/gw/web/action/PeopleAction_list.action",	
		url:"DutyInfoAction_list.action",
		 error: function (XMLHttpRequest, textStatus, errorThrown) {
             alert(textStatus);
             //alert("状态码"+XMLHttpRequest.readyState);
             //alert("内部服务器错误"+XMLHttpRequest.status);
             //msg = eval("(" + err + ")");
         },
		success:function(data) {
		    dutyinfodata = data;
		    $.jgrid.defaults.styleUI = 'Bootstrap';
		 // Configuration for jqGrid Example 2
		    $("#list1").jqGrid({
		        data: dutyinfodata,
		        datatype: "local",
		        //url: "../data/setpoint",
		        //datatype: "json",
		        height: "",
		        autowidth: true,
		        shrinkToFit: true,
		        rowNum: 10,
		        rowList: [10, 20, 30],
		        colNames: ['序号', '开始时间', "结束时间", '单位', "姓名", '联系方式'],
		        colModel: [
		            {
		                name: 'numid',
		                index: 'numid',
		                width: 5,
		                sortable: false,
					    hidden: true,
					    key:true
		            },
		            {
		                name: 'times',
		                index: 'times',
		                width: 15,
		                sorttype: "string",
		                formatter: "string"
		            },
		            {
		                name: 'timee',
		                index: 'timee',
		                width: 15
		            },
		            {
		                name: 'name',
		                index: 'name',
		                width: 40
		            },
		            {
		                name: 'people',
		                index: 'people',
		                width: 10,
		            },
		            {
		                name: 'phonenum',
		                index: 'phonenum',
		                width: 15,
		            }
		        ],
		        pager: "#pager1",
		        viewrecords: true,
		        caption: "",
		        add: true,
		        edit: true,
		        addtext: 'Add',
		        edittext: 'Edit',
		        hidegrid: false,
 
		    });
		 // Add selection  默认选择
		    //$("#list1").setSelection(4, fals);

		 // Setup buttons
            $("#list1").jqGrid('navGrid', '#pager1', {
                edit: false,
                add: false,
                del: false,
                search: false
            },
            {
                reloadAfterSubmit: true
            });
            jQuery("#list1").jqGrid("clearGridData");
            $("#list1").jqGrid('setGridParam', {
                data: dutyinfodata
            }).trigger("reloadGrid");
		    // Add responsive to jqGrid
		    $(window).bind('resize', function () {
		        var width = $('.jqGrid_wrapper').width();
		        $('#list1').setGridWidth(width);
		    });
		}
	});

};


function getXlsFromTbl(inTblId, inTblContainerId, title, rownumbers) {
    try {
        var allStr = "";
        var curStr = "";
        //alert("getXlsFromTbl");
        if (inTblId != null && inTblId != "" && inTblId != "null") {
            curStr = getTblData($('#' + inTblId), $('#' + inTblContainerId), rownumbers);
        }
        if (curStr != null) {
            allStr += curStr;
        }
        else {
            alert("你要导出的表不存在！");
            return;
        }
        var fileName = getExcelFileName(title);
        doFileExport(fileName, allStr);
    }
    catch (e) {
        alert("导出发生异常:" + e.name + "->" + e.description + "!");
    }
}
function getTblData(curTbl, curTblContainer, rownumbers) {

    var outStr = "";
    if (curTbl != null) {
        var rowdata = curTbl.getRowData();
        var Lenr = 1;

        for (i = 0; i < Lenr; i++) {
            //var Lenc = curTbl.rows(i).cells.length;
            var th;
            if (rownumbers == true) {
                th = curTblContainer.find('TH:not(:first-child)');
            }
            else {
                th = curTblContainer.find('TH');
            }
            th.each(function (index, element) {
                //alert($(element).text());
                //取得每行的列数
                var j = index + 1;
                var content = $(element).text();
                //alert(j + "|" + content);
                outStr += content + "\t";
                //赋值

            });
            outStr += "\r\n";
        }
        var tmp = "";
        for (i = 0; i < rowdata.length; i++) {
            var row = eval(rowdata[i]);
            for (each in row) {
                outStr += row[each] + "\t";
            }
            outStr += "\r\n";
        }


    }
    else {
        outStr = null;
        alert(inTbl + "不存在!");
    }
    return outStr;
}
function getExcelFileName(title) {
    var d = new Date();
    var curYear = d.getYear();
    var curMonth = "" + (d.getMonth() + 1);
    var curDate = "" + d.getDate();
    var curHour = "" + d.getHours();
    var curMinute = "" + d.getMinutes();
    var curSecond = "" + d.getSeconds();
    if (curMonth.length == 1) {
        curMonth = "0" + curMonth;
    }
    if (curDate.length == 1) {
        curDate = "0" + curDate;
    }
    if (curHour.length == 1) {
        curHour = "0" + curHour;
    }
    if (curMinute.length == 1) {
        curMinute = "0" + curMinute;
    }
    if (curSecond.length == 1) {
        curSecond = "0" + curSecond;
    }
    var fileName = title + "_" + curYear + curMonth + curDate + "_"
            + curHour + curMinute + curSecond + ".csv";
    //alert(fileName);
    return fileName;
}
function doFileExport(inName, inStr) {
    var xlsWin = null;
    if (!!document.all("HideFrm")) {
        xlsWin = HideFrm;
    }
    else {
        var width = 6;
        var height = 4;
        var openPara = "left=" + (window.screen.width / 2 - width / 2)
                + ",top=" + (window.screen.height / 2 - height / 2)
                + ",scrollbars=no,width=" + width + ",height=" + height;
        xlsWin = window.open("", "_blank", openPara);
    }
    xlsWin.document.write(inStr);
    xlsWin.document.close();
    xlsWin.document.execCommand('Saveas', true, inName);
    xlsWin.close();
}

